<?php
/**
 * User: Tegic
 * Date: 2018/6/1
 * Time: 15:11
 */

namespace app\api\validate;

use think\Db;
use think\Validate;

class User extends Validate
{
	protected $rule = [
		'username' => 'require|alphaDash|max:25|checkUser:username',
		'password' => 'require|alphaDash|min:6',
		'mobile'   => 'require|mobile|checkUser:mobile',
		'code'     => 'require|number|checkCode:1',
	];
	
	protected $message = [
		'username.require'   => '用户名必须',
		'username.alphaDash' => '用户名必须由字母或数字,下划线_及破折号-组合',
		'username.max'       => '用户名最多不能超过25个字符',
		'username.checkUser' => '该用户名已被注册',
		'password.require'   => '密码必须',
		'password.alphaDash' => '密码规则错误',
		'password.min'       => '密码必须6-20个字符',
		'mobile.require'     => '手机号码必须',
		'mobile.mobile'      => '手机号码格式不正确',
		'mobile.checkUser'   => '手机号码已被注册',
		'code.require'       => '验证码必须',
		'code.number'        => '验证码格式不正确',
		'code.checkCode'     => '验证码错误',
	];
	
	public $scene = [
		'login'        => [ 'mobile', 'password','code' ],
		'register'     => [ 'username', 'password', 'mobile', 'code' ],
	];
	
	/**
	 * 注册时验证用户名、电话号码是否为唯一
	 * @Function checkUser
	 *
	 * @param $username
	 *
	 * @return bool
	 * @Author   tegic
	 * @Time     2018/6/4 10:07
	 */
	protected function checkUser($value, $field)
	{
		$action = strtolower(request()->action());
		// 方法名不为注册的时候 直接验证通过
		$actions = [
			'register'
		];
		if (!in_array($action, $actions)) {
			return true;
		}
		$data = Db::name('user')->where($field, $value)->count();
		$ret  = ( $data == 0 ) ? true : false;
		return $ret;
	}
	
	/**
	 * 验证 验证码是否正确
	 * @Function checkCode
	 *
	 * @param $value
	 * @param $field
	 *
	 * @Author   tegic
	 * @Time     2018/6/4 12:44
	 */
	protected function checkCode($code, $field, $data)
	{
		$action = strtolower(request()->action());
		$type   = 1;
		switch ($action) {
			case 'register':
				$type = 1;
				break;
			case 'login':
				$type = 2;
				break;
		}
		$result = validate_code($data['mobile'], $type, $code);
		$ret    = ( $result === true ) ? true : false;
		return $ret;
	}
}